<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { login } from '@/api/auth'
import { findMenus } from '@/api/permission'
import { useUserStore } from '@/store/user'
import { useRolesStore } from '@/store/roles'
import { useMenusStore } from '@/store/menus'
import { hashEncrypt } from '@/utils/crypto'

const router = useRouter()

const ruleFormRef = ref<FormInstance>()
let submitting = ref(false)
//后端passport-local中 username password字段必须
const ruleForm = reactive({
  username: 'admin',
  password: 'admin123'
  // verifyCode: ''
})
const rules = reactive<FormRules>({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ]
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  submitting.value = true
  formEl.validate(async (valid) => {
    if (valid) {
      let data = Object.assign({}, ruleForm)
      data.password = await hashEncrypt(data.password)

      login(data).then(async (res) => {
        if (res.code === 200) {
          const data = res.data
          useUserStore().login(data)

          await useRolesStore().initRoles()

          await findMenus().then((mRes) => {
            if (mRes.code === 200) useMenusStore().SAVE_MENUS(mRes.data)
          })

          ElMessage({
            type: 'success',
            message: '登录成功'
          })
          router.push('/')
        } else {
          submitting.value = false
        }
      })
    } else {
      submitting.value = false
      console.log('失败!')
    }
  })
}
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    size="large"
    class="w-full"
    @keydown.enter="submitForm(ruleFormRef)"
  >
    <el-form-item prop="username">
      <el-input v-model="ruleForm.username" placeholder="用户名" prefix-icon="user" />
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="ruleForm.password"
        type="password"
        placeholder="密码"
        prefix-icon="lock"
        show-password
      />
    </el-form-item>
    <el-form-item>
      <el-button
        class="w-full"
        type="primary"
        :loading="submitting"
        :disabled="submitting"
        @click="submitForm(ruleFormRef)"
      >
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped></style>
